<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="充电站名称">
          <a-input placeholder="请输入充电站名称" v-decorator="['siteName', {rules: [{ required: true, message: '请输入充电站名称' }]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="简称">
          <a-input placeholder="请输入简称" v-decorator="['shortName', {rules: [{ required: true, message: '请输入充电站简称' }]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="省份">
         <!-- <a-input placeholder="请输入省份" v-decorator="['provinceId', {}]" />-->
          <a-select
            style="width: 100%"
            placeholder="请输入所属省"
            v-decorator="[ 'provinceId', {'initialValue':'17fcef40d4809404c3f4f4806cc05b59'}]">
            <a-select-option v-for="(province,provinceindex) in provinceList" :key="provinceindex.toString()" :value="province.id"  @click="queryCityList(province.id)">
              {{ province.provinceName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="市">
          <!--<a-input placeholder="请输入市" v-decorator="['cityId', {}]" />-->
          <a-select
            style="width: 100%"
            placeholder="请输入所属市"
            v-decorator="[ 'cityId', {'initialValue':'1397aa7b90e48972eb17d9aae32dfd4c'}]">
            <a-select-option v-for="(city,cityindex) in cityList" :key="cityindex.toString()" :value="city.id" @click="queryDistrictList(city.id)">
              {{ city.cityName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="区县">
          <!--<a-input placeholder="请输入区县" v-decorator="['districtId', {}]" />-->
          <a-select
            style="width: 100%"
            placeholder="请输入所属区"
            v-decorator="[ 'districtId', {rules: [{ required: true, message: '请选择区' }]}]">
            <a-select-option v-for="(district,districtindex) in districtList" :key="districtindex.toString()" :value="district.id">
              {{ district.districtName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="地理位置">
          <a-input placeholder="请输入地理位置" v-decorator="['sitePosition', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="X坐标">
          <a-input-number  v-decorator="[ 'coordinateX', {}]"  style="width: 300px"/>
          <a-button type="primary" @click="ztjwd">粘贴经纬度</a-button>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="Y坐标">
          <a-input-number v-decorator="[ 'coordinateY', {}]" style="width: 300px" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="直流桩台数">
          <a-input-number v-decorator="[ 'dcpileCount', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="交流桩台数">
          <a-input-number v-decorator="[ 'acpileCount', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="电价">
          <a-input placeholder="请输入电价" v-decorator="['chargingPrice', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="计费方式">
          <a-input placeholder="请输入计费方式" v-decorator="['chargeMode', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="停车收费">
          <a-input placeholder="请输入停车收费" v-decorator="['parkingCharge', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="对外开放">
          <a-input placeholder="请输入对外开放" v-decorator="['opening', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="功能设施">
          <a-input placeholder="请输入功能设施" v-decorator="['service', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="电话">
          <a-input placeholder="请输入电话" v-decorator="['tel', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="站点风采">
          <!--<a-input placeholder="请输入站点风采" v-decorator="['picPath', {}]" />-->
          <a-upload
            listType="picture-card"
            class="avatar-uploader"
            :showUploadList="false"
            :action="uploadAction"
            :data="{'isup':1}"
            :headers="headers"
            :beforeUpload="beforeUpload"
            @change="handleChange">
            <img v-if="picPath" :src="getAvatarView()" alt="站点风采" style="height:104px;max-width:300px"/>
            <div v-else>
              <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="监控IP">
          <a-input placeholder="请输入监控IP" v-decorator="['loginIp', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="监控端口">
          <a-input placeholder="请输入监控端口" v-decorator="['port', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="监控用户名">
          <a-input placeholder="请输入监控用户名" v-decorator="['userName', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="监控密码">
          <a-input placeholder="请输入监控密码" v-decorator="['password', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="设备端口">
          <a-input placeholder="请输入设备端口" v-decorator="['devicePort', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="电站描述">
          <a-input placeholder="请输入电站描述" v-decorator="['remark', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="运行状态">
          <!--<a-input placeholder="请输入运行状态" v-decorator="['status', {}]" />-->
          <a-select  v-decorator="[ 'status', {}]" placeholder="请选择运行状态">
            <a-select-option :value="1" >运行</a-select-option>
            <a-select-option :value="0">停止</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="删除状态">
          <a-input placeholder="请输入删除状态" v-decorator="['delFlag', {}]" />
        </a-form-item>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import Vue from 'vue'
  import { httpAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from "moment"
  import { postAction } from '@/api/manage'
  import { ACCESS_TOKEN } from "@/store/mutation-types"
  export default {
    name: "WxcChargingSiteModal",
    data () {
      return {
        title:"操作",
        visible: false,
        provinceList:[],
        cityList:[],
        districtList:[],
        provinceId:"",
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
        },
        picPath:"",
        url: {
          add: "/wxcchargingsite/wxcChargingSite/add",
          edit: "/wxcchargingsite/wxcChargingSite/edit",
          fileUpload: window._CONFIG['domianURL']+"/wxcchargingsite/wxcChargingSite/upload",
          provinceListUrl:"/dictionary/dictionary/provinceList",
          cityListUrl:"/dictionary/dictionary/cityList",
          districtListUrl:"/dictionary/dictionary/districtList",
          imgerver: window._CONFIG['domianURL']+"/sys/common/view",
        },
      }
    },
    created () {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token":token}
    },
    computed:{
      uploadAction:function () {
        return this.url.fileUpload;
      }
    },
    methods: {

      add () {
        this.picPath = "";
        this.edit({});
      },
      edit (record) {
        this.queryProvinceList();
        this.queryCityList('17fcef40d4809404c3f4f4806cc05b59');
        this.queryDistrictList('1397aa7b90e48972eb17d9aae32dfd4c');
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'siteName','shortName','provinceId','cityId','districtId','sitePosition','coordinateX','coordinateY','dcpileCount','acpileCount','chargingPrice','chargeMode','parkingCharge','opening','service','tel','picPath','loginIp','port','userName','password','devicePort','remark','status','delFlag'))
		  //时间格式化
        });
         if(this.model.picPath.length>0){
           this.picPath = "Has no pic url yet";
         }
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            //时间格式化

            console.log(formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })



          }
        })
      },
      handleCancel () {
        this.close()
      },
      queryProvinceList(){
        postAction(this.url.provinceListUrl).then((res)=>{
          if(res.success){
            this.provinceList = res.result;
          }else{
            console.log(res.message);
          }
        }).catch((err) => {
          this.$message.error("请求异常："+err)
        })
      },
      queryCityList(provinceId){
        let params = {provinceId:provinceId}
        postAction(this.url.cityListUrl,params).then((res)=>{
          if(res.success){
            this.cityList = res.result;
          }else{
            console.log(res.message);
          }
        }).catch((err) => {
          this.$message.error("请求异常："+err)
        })
      },
      queryDistrictList(cityId){
        let params = {cityId:cityId}
        postAction(this.url.districtListUrl,params).then((res)=>{
          if(res.success){
            this.districtList = res.result;
          }else{
            console.log(res.message);
          }
        }).catch((err) => {
          this.$message.error("请求异常："+err)
        })
      },

      beforeUpload: function(file){
        var fileType = file.type;
        if(fileType.indexOf('image')<0){
          this.$message.warning('请上传图片');
          return false;
        }
        //TODO 验证文件大小
      },
      handleChange (info) {
        this.picPath = "";
        if (info.file.status === 'uploading') {
          this.uploadLoading = true
          return
        }
        if (info.file.status === 'done') {
          var response = info.file.response;
          this.uploadLoading = false;
          console.log(response);
          if(response.success){
            this.model.picPath = response.message;
            this.picPath = "Has no pic url yet";
          }else{
            this.$message.warning(response.message);
          }
        }
      },
      getAvatarView(){
        return this.url.imgerver +"/"+ this.model.picPath;
      },
      ztjwd(){
        var pointText = this.getCookie('pointInput');
        if(pointText.length>0){
          alert(pointText.length);
          this.form.setFieldsValue({coordinateX:pointText.substring(0,pointText.indexOf(' '))});
          this.form.setFieldsValue({coordinateY:pointText.substring(pointText.indexOf(' ')+1, pointText.length)});
          console.log(this.getCookie('pointInput'));
        }else{
          alert("选择合适的坐标点");
        }



      },
      getCookie(c_name){
        if (document.cookie.length>0){
          //先查询cookie是否为空，为空就return ""　　　
          var c_start=document.cookie.indexOf(c_name + "=");
          //通过String对象的indexOf()来检查这个cookie是否存在，不存在就为 -1　　　　　
          if (c_start!=-1){
            c_start=c_start + c_name.length+1;　　//最后这个+1其实就是表示"="号啦，这样就获取到了cookie值的开始位置
            var c_end=document.cookie.indexOf(";",c_start);　　//其实我刚看见indexOf()第二个参数的时候猛然有点晕，后来想起来表示指定的开始索引的位置...这句是为了得到值的结束位置。因为需要考虑是否是最后一项，所以通过";"号是否存在来判断　　　　　　
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));　　//通过substring()得到了值。想了解unescape()得先知道escape()是做什么的，都是很重要的基础，想了解的可以搜索下，在文章结尾处也会进行讲解cookie编码细节　　　　
          }
        }
        return "";
      }

    },
  }
</script>

<style lang="less" scoped>

</style>